﻿﻿namespace Deixei.Infrastructure
{
    using System;
    using System.Collections.Generic;
    using System.Web.Http.Controllers;
    using System.Web.Mvc;
    using Microsoft.Practices.Unity;

    public class UnityDependencyScope 
    {
        protected IUnityContainer Container { get; private set; }
        protected IDependencyResolver Resolver { get; set; }

        public UnityDependencyScope(IUnityContainer container, IDependencyResolver resolver)
        {
            Container = container;
            Resolver = resolver;
        }

        public object GetService(Type serviceType)
        {
            if ( typeof(IHttpController).IsAssignableFrom(serviceType) )
            {
                return this.Container.Resolve(serviceType);
            }

            try
            {
                return this.Container.Resolve(serviceType);
            }
            catch
            {
                return this.Resolver.GetService(serviceType);
            }
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            try
            {
                return this.Container.ResolveAll(serviceType);
            }
            catch
            {
                return this.Resolver.GetServices(serviceType);
            }
        }

        public void Dispose()
        {
            Container.Dispose();
        }
    }

}
